import java.net.*;
import java.util.ArrayList;
import java.io.*;

public class HttpURLConnectionClient{

	final static String URLSTRING = "http://localhost:8080/?guess=";
	final static int ITERATIONS = 100;
	
	final static String CORRECTGUESS = "You made it!!!";
	final static String LOWGUESS = "Nope, guess higher";
	final static String HIGHGUESS = "Nope, guess lower";


	public static void main(String[] args){
		int amountOfGuesses = 0;
		int max = 100;
		int min = 0;
		boolean correct = false;
		String cookie = null;
		ArrayList<Integer> guesses = new ArrayList<Integer>();

		for(int i=0;i<ITERATIONS;i++){
			while(!correct){
				int guess = ((max+min)/2);
				URL url = null;
				try{
					url = new URL(URLSTRING+guess);
				}
				catch(MalformedURLException e){
					System.out.println(e.getMessage());
				}
				HttpURLConnection con = null;
				try{
					con = (HttpURLConnection)url.openConnection();
					if(cookie!=null){
						con.setRequestProperty("Cookie", cookie);
					}
				}
				catch(IOException e){
					System.out.println(e.getMessage());
				}
				con.setRequestProperty("User-Agent","Mozilla");
				try{
					con.connect();
				}
				catch(IOException e){
					System.out.println(e.getMessage());
				}
				BufferedReader infil = null;
				try{
					infil = new BufferedReader(new InputStreamReader(con.getInputStream()));
				}
				catch(IOException e){
					System.out.println(e.getMessage());
				}
				if(cookie==null){
					cookie = con.getHeaderField("Set-Cookie");
					cookie = cookie.substring(0, cookie.indexOf(";"));
				}
				String rad = null;
				try{
					while( (rad=infil.readLine()) != null){
						if(rad.contains(CORRECTGUESS)){
							//correct guess, reset everything
							guesses.add(amountOfGuesses);
							amountOfGuesses=0;
							max=100;
							min=0;
							correct=true;
						}
						if(rad.contains(LOWGUESS)){
							amountOfGuesses++;
							min=guess;
						}
						if(rad.contains(HIGHGUESS)){
							amountOfGuesses++;
							max=guess;
						}
					}
				}
				catch(IOException e){
					System.out.println(e.getMessage());
				}
			}
			correct = false;
		}
		double medel = 0;
		for(Integer i : guesses){
			medel += (((double)i)/((double)guesses.size()));
		}
		System.out.println("Medel: "+medel);
	}
}
